/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author snarasimhan
 */

import java.awt.*;  
import java.awt.event.*;  
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.*;  

public class LoginFrame extends javax.swing.JFrame {

    /**
     * Creates new form LoginFrame
     */
    public LoginFrame() {
        initComponents();
           setLocation(600, 200);
        /*Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        int X = (screen.width / 2) - (LoginFrame.WIDTH / 2); // Center horizontally.
        int Y = (screen.height / 2) - (LoginFrame.HEIGHT / 2); // Center vertically.
        setBounds(X,Y , LoginFrame.WIDTH ,LoginFrame.WIDTH );*/
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        JTextUserId = new javax.swing.JTextField();
        JPassword = new javax.swing.JPasswordField();
        jButtonCancel = new javax.swing.JButton();
        jButtonSubmit = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTxtDbIP = new javax.swing.JTextField();
        JTextErrorStr = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Login");
        setName("loginframe"); // NOI18N

        jLabel1.setText("User id:");

        jLabel2.setText("Password:");

        JTextUserId.setToolTipText("");
        JTextUserId.setName("txt_username"); // NOI18N
        JTextUserId.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JTextUserIdActionPerformed(evt);
            }
        });

        JPassword.setName("txt_passwd"); // NOI18N
        JPassword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JPasswordActionPerformed(evt);
            }
        });

        jButtonCancel.setText("Cancel");
        jButtonCancel.setName("btn_cancel"); // NOI18N
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });

        jButtonSubmit.setText("Submit");
        jButtonSubmit.setToolTipText("");
        jButtonSubmit.setName("btn_submit"); // NOI18N
        jButtonSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSubmitActionPerformed(evt);
            }
        });

        jLabel3.setText("Please enter login information");

        jLabel4.setText("Database IP:");

        jTxtDbIP.setText("localhost");
        jTxtDbIP.setName(""); // NOI18N

        JTextErrorStr.setBackground(new java.awt.Color(240, 240, 240));
        JTextErrorStr.setEditable(false);
        JTextErrorStr.setBorder(null);
        JTextErrorStr.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JTextErrorStrActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(87, 87, 87)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel4)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(JTextUserId)
                            .addComponent(JPassword)
                            .addComponent(jTxtDbIP, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(95, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButtonSubmit)
                .addGap(39, 39, 39)
                .addComponent(jButtonCancel)
                .addGap(80, 80, 80))
            .addComponent(JTextErrorStr)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(JTextUserId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(JPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTxtDbIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButtonSubmit, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButtonCancel, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(JTextErrorStr, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        getAccessibleContext().setAccessibleDescription("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
        
        //end application
        System.exit(0);
    }//GEN-LAST:event_jButtonCancelActionPerformed

    private void jButtonSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSubmitActionPerformed
        //connect to the database
       // validate login
        //lookup username as primary key...If exists valiate pasasword else throw record exception
        // if authentication passes, launch order entry application.
        
        Boolean connectError = false;       // Error flag
        Connection DBConn = null;           // MySQL connection handle
        Connection DBConn1 = null;
        String errString = null;            // String for displaying errors
        String msgString = null;            // String for displaying non-error messages
        ResultSet res = null;               // SQL query result set pointer
        //ResultSet res1 = null; 
        int ret;
        
        Statement s = null;                 // SQL statement pointer
        Statement s1 = null; 
        String userID = "";
        String password = "";
         
        String SQLServerIP = jTxtDbIP.getText();
        String sourceURL = "jdbc:mysql://" + SQLServerIP + ":3306/orderinfo";
        // Connect to the inventory database
        try
        {
 
            msgString = ">> Establishing connection with: " + sourceURL + "...";
            

            //create a connection to the db - note the default account is "remote"
            //and the password is "remote_pass" - you will have to set this
            //account up in your database

            DBConn = DriverManager.getConnection(sourceURL,"remote","remote_pass");

        } catch (Exception e) {

            JTextErrorStr.setText("Problem connecting to database " + e);
            connectError = true;

        } // end try-catch
        
         
        if ( !connectError )
        {
            try
            {
                s = DBConn.createStatement();
                res = s.executeQuery( "Select userid, passwd from app_users where userid = \"" + JTextUserId.getText() + "\"");
                //JTextErrorStr.setText("Select userid, passwd from app_users where userid = \" " + JTextUserId.getText() + "");
              
                while (res.next())
                {
                    userID = res.getString(1);
                    password = res.getString(2);
                    //JTextErrorStr.setText(res.getString(1));
                   // break; //we only need one row. So exit after one row

                } // while
                
              
            } catch (Exception e) {

                 JTextErrorStr.setText("ERROR: " + e);
               

            } // end try-catch
        } // if connect check
                                       
        if (userID.equals("")) {
                    JTextErrorStr.setText(JTextUserId.getText() + " does not exist");
        }
        else 
        { 
            if (!password.equals(JPassword.getText()))
                {
                     JTextErrorStr.setText(password + " - " + JPassword.getText() + ": Incorrect password for user id " + userID);
                } //end if
             else
                {
                    // test if the user has the IT Manager role
                    String role = null;
                    try {
                    s = DBConn.createStatement();
                    res = s.executeQuery( "Select userid, rolename from user_roles where userid = \"" + JTextUserId.getText() + "\"");
                
                    while (res.next())
                        {
                            userID = res.getString(1);
                            role = res.getString(2);      
                        } // while
                
                    } //end try
                    
                    catch (Exception e) {

                           JTextErrorStr.setText("ERROR: User not found in roles table " + e);
              
                    } // end catch
            
                    // test if the role of the user is IT manager     
                    if (!role.equals("IT Manager") )
                    {
                        JTextErrorStr.setText("ERROR: User role is not IT Manager ");
                    }  // end if 
                   
                    else {
                
                        try
                        {
                        s1 = DBConn.createStatement();
                        ret = s1.executeUpdate("UPDATE orderinfo.app_users set last_login_time = CURRENT_TIMESTAMP where userid = \'" + userID + "\'" );
                        //JTextErrorStr.setText("Select userid, passwd from app_users where userid = \" " + JTextUserId.getText() + "");
                        ret = s1.executeUpdate("Commit");
                        
                                      
                        } catch (Exception e1) {
                                JTextErrorStr.setText("ERROR: " + e1);
                        } // end try-catch
                        
                        this.setVisible(false);
                        NewJFrame logretrieve = new NewJFrame(SQLServerIP, userID);  
                        logretrieve.setVisible(true);  
                        logretrieve.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                
                    } //end else
                } //end else
                 
       } //end else
    }//GEN-LAST:event_jButtonSubmitActionPerformed

private void JTextUserIdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JTextUserIdActionPerformed
 // TODO add your handling code here:
}//GEN-LAST:event_JTextUserIdActionPerformed

private void JPasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JPasswordActionPerformed
 // TODO add your handling code here:
}//GEN-LAST:event_JPasswordActionPerformed

    private void JTextErrorStrActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JTextErrorStrActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_JTextErrorStrActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        /*try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
       */
       
        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new LoginFrame().setVisible(true);
                
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPasswordField JPassword;
    private javax.swing.JTextField JTextErrorStr;
    private javax.swing.JTextField JTextUserId;
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonSubmit;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField jTxtDbIP;
    // End of variables declaration//GEN-END:variables
}
